#!/usr/bin/env python
"""
PyLink-SR (Python Linked Software Radio System)
(c) Bob Cowdery (G3UKB) 2008

File: utils.py
Date: July 2008

This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

The author can be reached by email at

bob@g3ukb.co.uk

========================================================================
Module Description:
Useful stuff
"""

#-----------------------------------------------------------------------
# System imports

# Application imports

#-----------------------------------------------------------------------
# Common utility functions
def FreqToString(freq):
    """
    Convert a decimal frequency to zero padded MHz, KHz and Hz string values
    Inputs:
        freq    --- the frequency to be converted
    Outputs:
        return  --- s1,s2,s3 as MHz, KHz and Hz
    """
        
    # convert whole frequency to a string
    sFreq = '%(freq)f' %vars()
    l = len(sFreq)          # length of complete string
    o = sFreq.find('.')     # offset of decimal point
    if o == -1: 
        return "000", "000", "000"
        
    # zero pad to a full frequency length 
    #   i.e. from 3.9997 to 003.999700
    if o<3:     # need to left pad
        sFreq = sFreq.zfill(3-o+l)      # number of zeros to add plus total length
        l = len(sFreq)                  # recalc length
    if l<10:    # need to right pad
        sFreq = sFreq.ljust(10)         # space fill to 10 characters
        sFreq = sFreq.replace(' ','0')  # change spaces to zeros
        
    # unpack into fields and return
    return sFreq[:3], sFreq[4:7], sFreq[7:10]
 
#===========================================================================        
def StringToFreq(sMHz, sKHz, sHz):
    """
    Convert a string frequency to a decimal value
    Inputs:
        sMHz    --- the MHz value zero padded
        sKHz    --- the KHz value zero padded 
        sHz     --- the Hz value zero padded  
    Outputs:
        return  --- decimal frequency
    """
        
    # construct string and return float representation
    sFreq = sMHz + "." + sKHz + sHz
    return float(sFreq) 
